import requests
from pathlib import Path
import pandas as pd

# 设置关键词
keyword = '航拍美景'

# 创建目标文件夹
download_folder = Path(f'图片_{keyword}')
download_folder.mkdir(parents=True, exist_ok=True)

# 设置请求头信息
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36'}

# 从CSV文件中读取数据
df = pd.read_csv(f'图片_{keyword}.csv')

# 遍历读取的数据
for r in range(df.shape[0]):
    # 从数据中选取一行并转换成字典
    row = df.iloc[r].to_dict()
    # 提取“图片网址”和“图片类型”
    image_url = row['图片网址']
    image_type = row['图片类型']
    # 构造图片保存路径
    image_name = f'image_{r + 1}.{image_type}'
    image_path = download_folder / image_name
    # 跳过已存在的图片
    if image_path.exists():
        print(f'[{image_name}]已存在，跳过')
        continue
    # 下载不存在的图片
    try:
        # 对图片网址发起请求
        response = requests.get(url=image_url, headers=headers, timeout=(3.05, 10))
    except Exception as e:
        print(f'[{image_name}]请求失败：{image_url}')
    else:
        # 判断返回的数据是否为图片
        content_type = response.headers['Content-Type']
        if content_type.startswith('image/'):
            with open(file=image_path, mode='wb') as f:
                f.write(response.content)
            print(f'[{image_name}]下载完成：{image_url}')
        else:
            print(f'[{image_name}]下载失败：{image_url}')
